package org.algorithm;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

public class ServerAddressGet {

    public static void main(String []args) throws Exception {
        decode();
//        System.out.println(getRandomBase());
    }

    public static void decode() throws Exception {
        String  codeData = "ofAkzke9kIj+39avQGRIiNUuL8dYLQHKrCS79B0B1Zq8IOR8np5e9V7NMwTTEzcFlQuaubPaZGHY2VlGsuxtuSEU9QEW4eYcstVI9iCh23M";
        String nonce = "AbISZAAW";
        String secret = "bbx56q9ky1d3vgc9j7smz20l";
        System.out.println("解密数据为："+ decode(codeData,secret,nonce));
    }

    private static  String decode(String data,String deviceSecret,String nonce) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        String secret = deviceSecret+nonce;
        byte[] secretByte = Arrays.copyOf(secret.getBytes(), 32);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretByte, "AES"));
        byte[] encodeByte = Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8));
        byte[] encryptedBytes = cipher.doFinal(encodeByte);
        return new String(encryptedBytes);
    }

    public static void getRequest() throws Exception {
        String nonce = Base64.getEncoder().encodeToString(Arrays.copyOf(getCurrentMinte(),6));
        System.out.println("nonce为："+nonce);
        System.out.println("sign为："+Hmac.hmacSha256(nonce,"OTbBYEF9xn1AygDbfzIPufYAUQtxchwL"));
    }


    public static byte[] getCurrentMinte(){
        Long minite = System.currentTimeMillis()/60000;
        System.out.println("当前分钟数为："+minite);
        System.out.println("当前分钟数为："+minite.intValue());
        ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
        buffer.putInt(minite.intValue());
        return buffer.array();
    }

    public static String getRandomBase(){
        Long minite = System.currentTimeMillis()/60000;
        System.out.println("当前分钟数为："+minite);
        System.out.println("当前分钟数为："+minite.intValue());
        ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES+Short.BYTES);
        buffer.putInt(minite.intValue());
        buffer.putShort(Short.parseShort("22"));
        return Base64.getEncoder().withoutPadding().encodeToString(buffer.array());
    }

}
